## This software is licensed by the MIT License, see LICENSE file ##
##                                    Copyright © 2022 whitemangl ##

from datetime import datetime
from typing   import Union
from typing   import Dict
from typing   import List

from aiogram  import Bot
from aiogram  import Dispatcher
from aiogram.types import Message

from .Configuration import Configuration

class TGPBot(Bot):

    @classmethod
    async def __on_startup__(cls, bot: "TGPBot"):
        await bot.send_sys_message(f"{cls.__name__} запущен")

    @classmethod
    async def __on_shutdown__(cls, bot: "TGPBot"):
        await bot.send_sys_message(f"{cls.__name__} остановлен")

    async def send_sys_message(self, message:str):
        dt = str(datetime.now()).split('.', maxsplit=1)[0]
        await self.send_message(chat_id=self.admin_id, text=f"[{dt}] {message}")

    def __getattr__(self, attr):
        ret = self.__conf__.__getattr__(str(attr))
        return ret if ret else super().__getattribute__(attr)

    async def listen(self):
        await self.__dp__.start_polling(self)

    async def shutdown(self):
        await self.session.close()

    async def start(self):
        try:     await self.listen()
        finally: await self.shutdown()

    def __init__(self, conf: Union[Configuration, None] = None, dp:Union[Dispatcher, None] = None):
        self.__conf__ = conf if conf else Configuration()
        self.__dp__   = dp if dp else Dispatcher()

        self.__dp__.startup.register(self.__on_startup__)
        self.__dp__.shutdown.register(self.__on_shutdown__)

        self.event_message              = self.__dp__.message
        self.event_edited_message       = self.__dp__.edited_message
        self.event_channel_post         = self.__dp__.channel_post
        self.event_edited_channel_post  = self.__dp__.edited_channel_post
        self.event_inline_query         = self.__dp__.inline_query
        self.event_chosen_inline_result = self.__dp__.chosen_inline_result
        self.event_callback_query       = self.__dp__.callback_query
        self.event_shipping_query       = self.__dp__.shipping_query
        self.event_pre_checkout_query   = self.__dp__.pre_checkout_query
        self.event_poll                 = self.__dp__.poll
        self.event_poll_answer          = self.__dp__.poll_answer
        self.event_my_chat_member       = self.__dp__.my_chat_member
        self.event_chat_member          = self.__dp__.chat_member
        self.event_chat_join_request    = self.__dp__.chat_join_request
        self.event_errors               = self.__dp__.errors

        self.observers = self.__dp__.observers

        self.message_groups:Dict[Union[int, str], List[Message]] = dict()

        super().__init__(self.__conf__.token, parse_mode="HTML")
